//
//  LXRequest.swift
//  SwiftUIDemo
//
//  Created by zhouzuosong on 2020/11/9.
//  Copyright © 2020 Kael. All rights reserved.
//

import Foundation
import UIKit

// MARK: ------ 项目开关配置 ------
let isDemoProject = true
let isZKApp = true

// MARK: ------ 请求头工具类 ------
class LXRequestHeaderTool {
    
    let userDefualtsData = UserDefaults(suiteName: isDemoProject ? "group.widget.swiftui.demo" : (isZKApp ? "group.lexue.zhongkao" : "group.lexue.gaokao"))
    
    var deviceID : String {
        get {
            if let idfv = UIDevice.current.identifierForVendor?.uuidString {
                return idfv
            }
            return "*"
        }
    }
    var locations = ""
    var client = isZKApp ? "zk" : "gk"
    
    var version : String {
        get {
            let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
            return appVersion
        }
    }
    
    var platform : String {
        get {
            let deviceType = UIDevice.current.model
            return deviceType
        }
    }
    
    var grade = "j1"
    var leId : String {
        get {
            if isDemoProject {
                return "22308016"
            }
            return userDefualtsData?.string(forKey: "Widget_LeId") ?? ""
        }
    }
    
    var areaCode = ""
    var cityCode = ""
    
    let appKey = "131532197856977865"//生产环境：145612563999096833  测试环境：131532197856977865

    var deviceInfo:String {
        get {
            return "did:\(deviceID);manufacturer:apple;model:iphone;resolution:0x0;os:ios"
        }
    }
    
    var appInfo:String {
        get{
            return "client:\(client);version:\(version);channel:appStore;platform:\(platform)"
        }
    }
    
    var token:String {
        get {
            if isDemoProject {
                return "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsZUlkIjoiMTg0NTY1NCIsImV4cCI6MTYyMTg0Mjg4MiwidXNlcklkIjo4NDU2NTR9.enDoaZfkXmbsi-PVdFH7vbUUUuvMHjGoSNSViAX-SLM"
            }
            return userDefualtsData?.string(forKey: "Widget_Token") ?? ""
        }
    }
    
    var userInfo:String {
        get {
            var tempUserInfo = ""
            if grade.count > 0 {
                tempUserInfo = "grade:\(grade);"
            }
            if leId.count > 0 {
                tempUserInfo = "\(tempUserInfo)leId:\(leId)"
            }
            return tempUserInfo
        }
    }
    
    var location:String {
        get {
            var tempLocation:String = "position:0x0"
            if areaCode.count > 0 {
                tempLocation = "\(tempLocation);areaCode:\(areaCode);"
            }
            if cityCode.count > 0 {
                tempLocation = "\(tempLocation);areaCode:\(cityCode);"
            }
            return tempLocation
        }
    }
    
}

class LXRequest {
    static let share = LXRequest()
    var preDomain = ""
    var path = ""
    var query = ""

    // MARK:- get请求

    func getWithPath(path: String,paras: Dictionary<String,Any>?,success: @escaping ((_ result: Any, _ data:Data) -> ()),failure: @escaping ((_ error: Error) -> ())) {
        
        var i = 0

        var address = path

        if let paras = paras {
            for (key,value) in paras {
                if i == 0 {
                    address += "?\(key)=\(value)"
                }else {
                    address += "&\(key)=\(value)"
                }
                i += 1
            }
        }
        
        let url = URL(string: address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
        let session = URLSession.shared
        
        var urlrequest = URLRequest.init(url: url!)
        urlrequest = configStaticHeader(with: &urlrequest)
        urlrequest = configDynamicHeader(with: &urlrequest)
        
        let requestTask = session.dataTask(with: urlrequest) { (data, respond, error) in
            if let data = data {
                if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments){
                    success(result,data)
                }

            }else {
                failure(error!)
            }
            
        }
        
        requestTask.resume()
    }
    
    // MARK:- post请求

    func postWithPath(path: String,paras: Dictionary<String,Any>?,success: @escaping ((_ result: Any) -> ()),failure: @escaping ((_ error: Error) -> ())) {
        var i = 0

        var address: String = ""
        if let paras = paras {
            for (key,value) in paras {
                if i == 0 {
                    address += "\(key)=\(value)"

                }else {
                    address += "&\(key)=\(value)"
                }
                i += 1
            }

        }

        let url = URL(string: path)

        var request = URLRequest.init(url: url!)

        request.httpMethod = "POST"

        print(address)

        request.httpBody = address.data(using: .utf8)

        let session = URLSession.shared

        let dataTask = session.dataTask(with: request) { (data, respond, error) in
            if let data = data {
                if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) {
                    success(result)
                }
            }else {
                failure(error!)
            }
        }

        dataTask.resume()

    }
    
    func configStaticHeader(with urlrequest: inout URLRequest ) -> URLRequest {
        let headerTool = LXRequestHeaderTool()
        urlrequest.addValue(headerTool.deviceInfo, forHTTPHeaderField: "deviceInfo")
        urlrequest.addValue(headerTool.appInfo, forHTTPHeaderField: "appInfo")
        urlrequest.addValue(headerTool.appKey, forHTTPHeaderField: "appkey")

        return urlrequest
    }
    
    func configDynamicHeader(with urlrequest: inout URLRequest ) -> URLRequest {
        let headerTool = LXRequestHeaderTool()
        urlrequest.addValue(headerTool.token, forHTTPHeaderField: "token")
        urlrequest.addValue(headerTool.userInfo, forHTTPHeaderField: "userInfo")
        urlrequest.addValue(headerTool.location, forHTTPHeaderField: "location")
        
        return urlrequest
    }
    
}



